package com.x2.config;

import com.x2.core.auth.cache.SessionManager;
import com.x2.core.auth.entrypoint.JwtAuthenticationEntryPoint;
import com.x2.core.auth.filter.JwtAuthorizationTokenFilter;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.ArrayList;
import java.util.List;

@Configuration
@EnableWebSecurity    // 添加 security 过滤器
@EnableGlobalMethodSecurity(prePostEnabled = true)    // 启用方法级别的权限认证
public class SpringSecurityConfig {

    //资源文件目录
    public static List<String> regs = new ArrayList<>();

    /**
     * 初始化资源文件目录
     */
    static {
        regs.add("/assets/**");
        regs.add("/favicon.ico");
    }

    /**
     * 是否是资源目录
     *
     * @param request
     * @return
     */
    private boolean isResource(HttpServletRequest request) {
        //过滤静态资源
        for (String reg : regs) {
            if (new AntPathMatcher().match(reg, request.getServletPath())) {
                return true;
            }
        }
        return false;
    }


    @Autowired
    private JwtAuthenticationEntryPoint jwtAuthError;

    @Autowired
    private SessionManager sessionManager;

    /**
     * 获取AuthenticationManager（认证管理器），登录时认证使用
     *
     * @param authenticationConfiguration
     * @return
     * @throws Exception
     */
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }


    /**
     * 非资源文件所有过滤器
     *
     * @param http
     * @return
     * @throws Exception
     */
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        // 基于 token，不需要 csrf
        http.csrf().disable().headers().frameOptions().disable();
        http.cors().disable();
        http.logout().disable();
        http.formLogin().disable();
        // 基于 token，不需要 session
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
//                // 设置 jwtAuthError 处理认证失败、鉴权失败
                .exceptionHandling().authenticationEntryPoint(jwtAuthError).accessDeniedHandler(jwtAuthError).and()
                // 下面开始设置权限
                .authorizeRequests(authorize -> authorize
                                //禁用匿名用户
                                //.anonymous().disable()
                                .requestMatchers("/").permitAll()
                                .requestMatchers("/druid/**").permitAll()
                                .requestMatchers("/login").permitAll()
                                .requestMatchers("/kaptcha").permitAll()
                                // 其他地址的访问均需验证权限
                                .anyRequest().authenticated()
                        // 添加 JWT 过滤器，JWT 过滤器在用户名密码认证过滤器之前

                );
        http.addFilterBefore(new JwtAuthorizationTokenFilter(sessionManager), UsernamePasswordAuthenticationFilter.class);

        //资源目录跳过
        http.securityMatcher(new RequestMatcher() {
            @Override
            public boolean matches(HttpServletRequest request) {
                return !isResource(request);
            }

        });
        SecurityFilterChain filterChain = http.build();

        return filterChain;
    }


    /**
     * 配置跨源访问(CORS)
     *
     * @return
     */
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
        return source;
    }

}